using System.Text;
using LDNS.Interfaces;
using LDNS.SDK.Commands.Models;
using LDNS.Utilities;

namespace LDNS.Commands
{
    /// <summary>
    /// 获取缓存统计命令处理器
    /// 处理GET_CACHE_STATS命令，获取DNS缓存统计信息
    /// 作者：huobing
    /// </summary>
    public class GetCacheStatsCommandHandler : CommandHandlerBase<GetCacheStatsCommand, GetCacheStatsResult>
    {
        private readonly IDnsService _dnsService;
        
        /// <summary>
        /// 命令名称
        /// </summary>
        public override string CommandName => GetCacheStatsCommand.NAME;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dnsService">DNS服务实例</param>
        public GetCacheStatsCommandHandler(IDnsService dnsService)
        {
            _dnsService = dnsService;
        }
        
        /// <summary>
        /// 执行命令
        /// </summary>
        /// <param name="args">命令参数</param>
        /// <returns>执行结果</returns>
        public override BaseCommandResult Execute(string[] args)
        {
            try
            {
                // 获取完整的缓存统计信息
                var cacheStats = DnsCacheManager.Instance.CacheStatistics;
                
                // 创建并填充结果对象
                var result = new GetCacheStatsResult
                {
                    TotalItems = cacheStats.TotalItems,
                    HitRate = cacheStats.HitRate / 100.0, // 转换为小数形式（0-1）
                    CacheSize = cacheStats.TotalSize,
                    RecentlyAccessedCount = cacheStats.CacheHits // 暂时设为0，可以在DnsCacheManager中实现
                };
                
                // 收集记录类型分布
                var recordTypeDistribution = new Dictionary<string, int>();
                foreach (var cacheItem in DnsCacheManager.Instance.DnsCache)
                {
                    string recordType = cacheItem.Value.RecordType;
                    if (recordTypeDistribution.ContainsKey(recordType))
                    {
                        recordTypeDistribution[recordType]++;
                    }
                    else
                    {
                        recordTypeDistribution[recordType] = 1;
                    }
                }
                result.RecordTypeDistribution = recordTypeDistribution;
                
                return result;
            }
            catch (System.Exception ex)
            {
                return CreateErrorResult($"获取缓存统计信息失败: {ex.Message}");
            }
        }
    }
}